package com.kitty.game.activity.service.time;

import com.kitty.common.core.SchedulerManager;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.base.service.BagService;
import com.kitty.game.boss.config.BossSet;
import com.kitty.game.boss.model.BossFightParam;
import com.kitty.game.boss.model.BossParam;
import com.kitty.game.boss.service.NewBossService;
import com.kitty.game.chat.service.ChatService;
import com.kitty.game.config.NPC;
import com.kitty.game.enter.Position;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.fight.bean.Fight;
import com.kitty.game.fight.service.FightService;
import com.kitty.game.house.HouseController;
import com.kitty.game.npc.model.NpcButton;
import com.kitty.game.reward.service.RewardService;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.team.model.Team;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.TimeUtil;
import com.kitty.listener.event.FightEndEvent;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.message.MessagePusher;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**攻城怪物白骨精处理类*/
@Component
public class BaiGuJing extends FightActivityHandler {
    Logger logger = LoggerFactory.getLogger(HouseController.class);
    @Autowired
    FightService fightService;
    /**刷新地图*/
    private static final List<Integer> MAPIDS = Arrays.asList(12000);
    /**每个地图显示的怪物数量*/
    private static final int PIRATE_COUNT_PER_MAP = 10;
    private static final String PIRATE_NAME = "白骨精";
    private static final int PIRATE_ICON = 6280;
    private static final int ACCEPT_MIN_LEVEL = 60;
    /**攻城怪物持续时间，单位毫秒*/
    private static final long PIRATE_CONTINUED_TIME = 50 * TimeUtil.ONE_MINUTE;
    /**最少组队人数*/
    private static final int MIN_TEAM_COUNT = 1;
    private static final String KILL_MESSAGE ="刚刚有#R1#n名#R八星白骨精#n被我们的英雄消灭了！真是了不起啊！尚有#R{0}#n名#R八星白骨精#n仍在#Z十里坡#Z作乱，请众位英雄继续加油啊！";
    private static final String PIRATE_COME_NUMOR = "攻城怪物#R八星白骨精#n将在#Z十里坡#Z降临，各位道友可前往挑战，星级越高奖励越好，怪也会更厉害";
    private static final String PIRATE_ALL_KILL_NUMOR = "八星白骨精已全部被消灭！看来中洲大陆真是能人辈出啊！";
    private static final String CONTENT = "爷们刚想着抢点东西，你就送上门来了！[我要为民除害/" + NpcButton.FIGHT_TO_BAIGUJING.getKey() + "][赶紧逃命/逃命]";
    private static final String IN_FIGHT = "急什么！送钱也要一个一个来！[离开]";
    private static final String TEAM_COUNT_NOT_ENOUGH = "请至少组队1人！[离开]";
    private static final String TEAM_LEVEL_NOT_ENOUGH = "看你们这么嫩，想来也没什么可搜刮的，你们还是躲一边玩去吧！（队伍中#Y{0}#n的等级不足{1}级，能力不足以除害）[离开]";

    /**刷新攻城怪物，显示在对应的地图上*/
    public void flushPirate() {
        /**先让之前刷新的攻城怪物消失*/
        //hidePirate();

        /**遍历刷新攻城怪物*/
        for (int mapId : MAPIDS) {
            for (int i=0; i<PIRATE_COUNT_PER_MAP; i++) {
                createPirate(mapId);
            }
        }

        /**发谣言*/
          SpringUtils.getBean(ChatService.class).sendNumor(PIRATE_COME_NUMOR, Const.BRODCAST_MSG_TYPE_ROLE);
//        String msg = "#Y《天兵神将》活动将于10分钟后在#R无名小镇#Y下凡人界，各位道友可前往挑战";
//        SpringUtils.getBean(ChatService.class).sendAdnotice(PIRATE_COME_NUMOR);
        //SpringUtils.getBean(ChatService.class).sendNumor(PIRATE_COME_NUMOR, Const.BRODCAST_MSG_TYPE_ROLE);

        /**增加定时任务，持续时间结束后删除*/
        SchedulerManager.getInstance().schedule(() -> hidePirate(), PIRATE_CONTINUED_TIME);
    }

    /**在地图上刷新一个攻城怪物*/
    private void createPirate(int mapId) {
        Position position = getRandomPosition(mapId);

        NPC npc = new NPC();
        npc.setIcon(PIRATE_ICON);

        npc.setId(SpringUtils.getBean(NewBossService.class).getTempNpcId());
        npc.setX(position.getX());
        npc.setY(position.getY());
        npc.setFangxiang((short) new Random().nextInt(8));/**随机方向*/
        npc.setMapId(mapId);
        npc.setCreateTime(System.currentTimeMillis());
        npc.setEndTime(npc.getCreateTime() + PIRATE_CONTINUED_TIME);
        npc.setType(NPC.TYPE_TIANBINGSHENJIANG);
        npc.setContent(CONTENT);
        npc.setName(PIRATE_NAME);
        npc.setBossSetName(PIRATE_NAME);

        bossService.broadcastNpcShow(null, npc);

        DataCache.TIANBING_NPCS.put(npc.getId(), npc);

        Set<Integer> set = DataCache.TIANBING_MAP_NPC.get(mapId);
        if (set == null) {
            set = new HashSet<>();
            DataCache.TIANBING_MAP_NPC.put(mapId, set);
        }
        DataCache.TIANBING_MAP_NPC.get(mapId).add(npc.getId());
    }

    /**使所有海盗在对应地图上消失*/
    public void hidePirate() {
        logger.warn("删除npc==白骨精");
        if (DataCache.TIANBING_NPCS.size() > 0) {
            List<NPC> list = new ArrayList<>(DataCache.TIANBING_NPCS.values());
            for (NPC npc : list) {
                if (npc.isInFight()) {
                    /**在战斗中隐藏*/
                    bossService.broadcastNpcHide(null, npc);
                } else {
                    clearPirate(npc);
                }
            }
        }
    }

    /**移除海盗*/
    private void clearPirate(NPC npc) {

        if (npc == null) {return ;}
        logger.debug("移除被消灭的白骨精=={}{}",npc.getId(),npc.getName());

        DataCache.TIANBING_NPCS.remove(npc.getId());
        Set<Integer> set1 = DataCache.TIANBING_MAP_NPC.get(npc.getMapId());
        if (set1 != null) {
            set1.remove(npc.getId());
        }
        removeUsedPosition(npc.getMapId(), npc.getX(), npc.getY());

        bossService.broadcastNpcHide(null, npc);
    }

    @Override
    protected String getNpcContent(Role role, NPC bossNpc) {
        logger.debug("返回对话" + bossNpc.getName());
        return bossNpc.getContent();
//        return null;
    }


    @Override
    public String getNpcContentNotFight(Role role, NPC bossNpc) {

//        if(role.getActivity().getTbsjCount() >= Const.TIANBINGSHENJIANG_COUNT){
//            return "今日挑战次数已用完" + Const.LEAVE_BUTTON;
//        }

        /**检测是否在战斗中*/
        if (bossNpc.isInFight()) {
            return IN_FIGHT;
        }

        /**检测队伍人数*/
        int teamCount = teamService.getTeamCount(role);
        if (teamCount < MIN_TEAM_COUNT) {
            return TEAM_COUNT_NOT_ENOUGH;
        }

        /**检测等级*/
        Team team = teamService.getTeam(role.getRoleId());
        String names = teamService.checkMember(team, memberRole -> memberRole.getLevel() < ACCEPT_MIN_LEVEL);
        if (names != null) {
            return MessageFormat.format(TEAM_LEVEL_NOT_ENOUGH, names, ACCEPT_MIN_LEVEL);
        }


        return null;
    }


    @Override
    public void doStartFight(Role role, NPC bossNpc) {
        List<BossParam> bossParamList = newBossParamList(role, bossNpc);

        BossFightParam bossFightParam = new BossFightParam(bossParamList, getFightType(role));
        bossFightParam.setNpcId(bossNpc.getId());
        Fight fight = bossService.startFightToBoss(role, bossFightParam);

//        Team team = teamService.getTeam(role.getRoleId());
//        List<Member> list = team.getList();
//        RoleService roleService = SpringUtils.getRoleService();
//        for (Member member: list) {
//            Role memberRole = roleService.getOnlinePlayer(member.getRoleId());
//            memberRole.getActivity().setPirate_count(memberRole.getActivity().getPirate_count() + 1);
//        }
    }

    @Override
    protected int getFightType(Role role) {
        return Const.baigu;
    }

    @Override
    protected NPC getBossNpc(int npcId) {
        return DataCache.TIANBING_NPCS.get(npcId);
    }

    @Override
    protected void clearNpcAfterWin(Role role, NPC bossNpc) {
        clearPirateAfterFightWin(bossNpc);
    }

    private List<BossParam> newBossParamList(Role role, NPC bossNpc) {
        List<BossParam> bossParamList = new ArrayList<>();
        int count = getBossCount(role);

        /**npc对应的加在第1个*/
        BossSet bossSet = bossService.getBossSet(bossNpc.getBossSetName());
        bossParamList.add(new BossParam(bossSet, bossNpc.getName()));

        /**加count-1个*/
        String bName = "";
        for (int i=1; i<count; i++) {
            if(i == 1){
                bName = "护体之灵";
            }
            bossSet = bossService.getBossSet(bName);
            bossParamList.add(new BossParam(bossSet, bossSet.getName()));
        }

        return bossParamList;
    }

    @Override
    public int getBossCount(Role role) {
        /**最多有10个*/
        int allCount = 10;
        int teamCount = teamService.getTeamCount(role);

        /**根据组队数量计算怪的数量*/
        int count = 0;
        if (teamCount <= 3) {
            int minCount = 10;
            count = ThreadLocalRandom.current().nextInt(allCount - minCount + 1)  + minCount;
        } else if (teamCount == 4){
            int minCount = 10;
            count = ThreadLocalRandom.current().nextInt(allCount - minCount + 1)  + (minCount);
        } else {
            count = allCount;
        }
        return count;
    }

    /**在战斗胜利后移除白骨精*/
    private void clearPirateAfterFightWin(NPC npc) {
        int oldPirateCount = DataCache.TIANBING_NPCS.size();
        /**移除百年刺猬精操作*/
        clearPirate(npc);
        int newPirateCount = DataCache.TIANBING_NPCS.size();

        if (newPirateCount != oldPirateCount) {
            if (newPirateCount > 0) {
                /**不是最后一个时，发的谣言*/
                String msg = MessageFormat.format(KILL_MESSAGE, newPirateCount);
                SpringUtils.getChatService().sendNumor(msg, Const.BRODCAST_MSG_TYPE_ROLE);
            } else {
                /**杀死最后一个时，发的谣言*/
                if (oldPirateCount == 1 && newPirateCount == 0) {
                    SpringUtils.getChatService().sendNumor(PIRATE_ALL_KILL_NUMOR, Const.BRODCAST_MSG_TYPE_ROLE);
                }
            }
        }
    }

    private byte getRoleRemainCount(Role role) {
        return (byte) SpringUtils.getActivityService().getRemainCount(role, ActivityType.guaiwugongcheng);
    }
    /**给奖励*/
    public void giveReward(Role role, FightEndEvent fightEndEvent, NPC bossNpc) {
        int count = getRoleRemainCount(role);
        if (count > 0) {/*次数在npc类 这个0只是取数*/
            if (!teamService.isInTeam(role)) {
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("离队无法获得奖励"));
                return;
            }
            // 这里改成公共获取配置 经验，道行，武学 奖励。 不再单独写
            fightService.sendBossBasicsReward(role,fightEndEvent);
            SpringUtils.getActivityService().addFinishCount(role, ActivityType.guaiwugongcheng, 1);
            fightService.sendBossExtReward(role,fightEndEvent);


        } else{
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("今日挑战次数以达到上限！不会给奖励"));
            return;
        }
    }

    @Override
    protected void clearNpcTimeOut(NPC npc) {
        clearPirate(npc);
    }

}
